package com.lingjtx.common.redis.stream;

import com.alibaba.fastjson2.JSON;
import org.redisson.api.RStream;
import org.redisson.api.RedissonClient;
import org.redisson.api.stream.StreamAddArgs;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class RedisStreamPublisher {

    private final RedissonClient redissonClient;

    public RedisStreamPublisher(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    public void publish(RedisStreamTypedEvent event) {
        String streamKey = event.getType() + ".stream";

        Map<String, String> data = new HashMap<>();
        data.put("eventType", event.getClass().getName());
        data.put("payload", JSON.toJSONString(event));

        RStream<String, String> stream = redissonClient.getStream(streamKey);
        StreamAddArgs<String, String> args = StreamAddArgs.entries(data);
        stream.add(args);
    }
}
